# coding: utf8
from gluon.contrib.markdown import WIKI
#from gluon.contrib.markdown import MARKMIN
FLATPAGE_VIEW = 'plugin_uc_flatpage.html'
if session._language is None:
    session._language = 'en'
import os
cwd = os.getcwd()
format=MARKMIN
plugin_name = 'plugin_uc_flatpage'

PLUGIN_NAME = APPLICATION_CONTROLER = 'plugin_uc_flatpage'

db.define_table('plugin_flatpage',
    Field('controller'),
    Field('function'),
    Field('arg'),
    Field('title'),
    Field('subtitle'),
    Field('view', default=FLATPAGE_VIEW),
    Field('format', requires=IS_IN_SET(['MARKMIN', 'WIKI', 'HTML']), default='MARKMIN'),
    Field('lang'),
    Field('body', 'text'),
    Field('created_on', 'datetime', default=request.now, required=False),
    Field('created_by', db.auth_user, default=auth.user and auth.user.id or None, required=False),
)


def plugin_flatpage():
    title = subtitle = format = view = body = ""

    if not request.vars.action or request.vars.action in ('edit', 'id'):
        # search flatpage according to the current request
        query = db.plugin_flatpage.controller==request.controller
        query &= db.plugin_flatpage.function==request.function
        query &= db.plugin_flatpage.arg==(request.args and request.args[0])
        if 'id' in request.vars:
            # request an specific version
            query &= db.plugin_flatpage.id==request.vars['id']
            response.flash = T("Viewing page version: %s") % request.vars['id']
        query &= db.plugin_flatpage.lang==session._language
        # execute the query, fetch one record (if any)
        rows = db(query).select(orderby=~db.plugin_flatpage.created_on, limitby=(0, 1))
        if rows:
            flatpage = rows[0] 
            view = flatpage.view
            title = flatpage.title
            subtitle = flatpage.subtitle
            format = flatpage.format
            body = flatpage.body
        else:
            #TODO: define a "create page" message for not-found uc_flatpage
            response.flash = T("Page Not Found!")
#            format = "WIKI"
            format = "MARKMIN"
            view = FLATPAGE_VIEW
    elif request.vars.action and request.vars.action=='history':
        # search flatpage history
        query = db.plugin_flatpage.controller==request.controller
        query &= db.plugin_flatpage.function==request.function
        if request.args:
            query &= db.plugin_flatpage.arg==request.args[0]
        query &= db.plugin_flatpage.lang==session._language
        query &= db.plugin_flatpage.created_by==db.auth_user.id
        # execute the query, fetch one record (if any)
        rows = db(query).select(db.plugin_flatpage.id, 
                   db.plugin_flatpage.title, db.plugin_flatpage.subtitle, 
                   db.plugin_flatpage.created_on, db.auth_user.first_name, db.auth_user.last_name,
                   orderby=~db.plugin_flatpage.created_on)
        if rows:
            title = rows[0].plugin_flatpage.title
            subtitle = rows[0].plugin_flatpage.subtitle
            body = TABLE(TR(TH(T("Id")),TH(T("Title")),TH(T("Subtitle")),TH(T("Date")),TH(T("User"))),
                    *[TR(TD(A(row.plugin_flatpage.id, _href=URL(r=request,vars={'id': row.plugin_flatpage.id}))),
                         TD(row.plugin_flatpage.title),TD(row.plugin_flatpage.subtitle),
                         TD(row.plugin_flatpage.created_on),TD(row.auth_user.first_name, row.auth_user.last_name)) for row in rows])
            response.flash = T("Page History")
    else:
        view = request.vars.view
        title = request.vars.title
        subtitle = request.vars.subtitle
        format = request.vars.format
        body = request.vars.body
        if 'action' in request.vars and request.vars.action=='convert':
            if format=='HTML':
                body = WIKI(body)
            else:
                try:
                    html2text= local_import('html2text')
                    body = html2text.html2text(body.decode("utf8")).encode("utf8")
                except:
                    pass

    if not auth.has_membership(auth.id_group('plugin_uc_flatpage')):
        form = None
    elif 'action' in request.vars and request.vars.action in('edit', 'preview', 'convert', 'save'):
        form = FORM(TABLE(
                   TR(T("Title"), INPUT(_type="text", _name="title", value=title)),
                   TR(T("Subtitle"), INPUT(_type="text", _name="subtitle", value=subtitle)),
                   TR(T("Body"), TEXTAREA(_name="body", value=body, _id="wysiwyg")), 
                   TR(T("Format"), SELECT(
                          [OPTION(v, _value=k) for (k, v) in db.plugin_flatpage.format.requires.options()], 
                          value=format, _name="format", requires=db.plugin_flatpage.format.requires,
                          _onchange="this.form.action.value='convert';this.form.submit();")),  
                   TR(T("View"), INPUT(_type="text", _name="view", value=view)),
                   TR("",(INPUT(_type='hidden', _name='action', _id='action', _value="save"),
                       INPUT(_type='button', _value=T('Preview'),
                                   _onclick="this.form.action.value='preview';this.form.submit();"),
                       INPUT(_type="submit", _value=T("Save")),
                       INPUT(_type='button', _value=T('Cancel'),
                                   _onclick="this.form.action.value='';this.form.submit();"),
                        ))))

        if form.accepts(request.vars, session):
            if request.vars.action=='save':
                page_id = db.plugin_flatpage.insert(
                   controller=request.controller,
                   function=request.function,
                   arg=request.args and request.args[0],
                   title=form.vars.title,
                   subtitle=form.vars.subtitle,
                   view=form.vars.view,
                   format=form.vars.format,
                   lang=session._language,
                   body=form.vars.body)
                response.flash = T("Page saved")
                form = None
            elif request.vars.action=='convert':
                response.flash = T("Page format converted!")
                body = ""
            else:
                response.flash = T("Page Preview")
        else:
            if form.errors:
                response.flash = T("Errors!")
            else:
                response.flash = T("Edit Page")
            body = ""
    else:
        form = FORM(INPUT(_type='hidden', _name='action', _id='action', _value="edit"),
                INPUT(_type="submit", _value=T("Edit"), ),
                INPUT(_type='button', _value=T("History"),
                      _onclick="this.form.action.value='history';this.form.submit();"))

    response.view = view or FLATPAGE_VIEW
    response.title = title
    response.subtitle = subtitle
    if format=='MARKMIN':
        body = MARKMIN(body)
    elif format=='WIKI':
        body = WIKI(body)
    elif format=='HTML':
        body = XML(body)


    return dict(body=body, form=form, format=format)

############################################
# init_0_add_auth_group_0_plugin_uc_flatpage
#
# -*- coding: utf-8 -*-
# Adapted by Christopher Steel of Voice of Access as automated admin user creater.

# Original liscense:

# Instant Press, site that work out the box. Blog system for Web2py Framework 
# Site: http://www.instant2press.com
# Site: http://code.google.com/p/instant-press/
# Copyright (c) 2010- Mulone, Pablo Martín (mulone.martin@gmail.com)
# License: GPL, General Public License v.2
# Visit: www.web2py.com or Groups: http://groups.google.com/group/web2py and http://groups.google.com/group/web2py-usuarios  

#ATTENTION!: do not use this method to add users, instead use
#registration, this is for testing purpose

def _fill_new_user(first_name,last_name,email,passw):    
    users = db(db.auth_user.email==email).select() #GAE
    if users:
        return users[0].id
    else:
        my_crypt = CRYPT(key=auth.settings.hmac_key)
        crypt_pass = my_crypt(passw)[0]        
        id_user= db.auth_user.insert(
                                   first_name=first_name,
                                   last_name=last_name,
                                   email = email,
                                   password = crypt_pass                             
                                   )
        return id_user

def _fill_require_admin_group():    
    group_admin = db(db.auth_group.role==DEFAULT_GROUPADMIN).select()
    if group_admin:
        return group_admin[0].id
    else:       
        id_group_admin = db.auth_group.insert(
                                    role=DEFAULT_GROUPADMIN,
                                    description = 'This is admin group'
                                    )
        return id_group_admin
    
def _is_no_user_in_db():        
    users_count = db(db.auth_user.id>0).count() #GAE
    if (users_count>0): 
        return False
    else:
        return True

def _fill_required_admin():
    id_group_admin = _fill_require_admin_group()    
    users_count = db(db.auth_user.id>0).count() #GAE
    if (users_count==0): #if no users
        id_user = _fill_new_user('John','Doe',DEFAULT_ADMIN_EMAIL,DEFAULT_ADMIN_PASSWORD)
        auth.add_membership(id_group_admin, id_user)  
        
    
def _fill_get_admin_guy():
    users = db(db.auth_user.email==DEFAULT_ADMIN_EMAIL).select() #GAE
    if users:
        return users[0].id
    else:
        return 0

def _fill_test_users():
    iduser = _fill_new_user('Chris','Mills','chris@nobody.com','somepasswordhere')
    iduser = _fill_new_user('Chris','Mills2','chris1@nobody.com','somepasswordhere')
    iduser = _fill_new_user('Chris','Mills3','chris2@nobody.com','somepasswordhere')
# coding: utf8

########################################################
#init_0_create_uc_flatpage_content_0_plugin_uc_flatpage.py
#
# This code was lifted from the instant-press application by Pablo Martin.
# Mucho hackyness modification where made by Christopher Steel of Voice of Access.
# Please address any issues with this application to Christopher.Steel@VoiceOfAcess.org
#
# The code remains:
# License: GPL, General Public License v.2
#
# Here is Pablo's Header from the original code.
#
# -*- coding: utf-8 -*-
# Instant Press, site that work out the box. Blog system for Web2py Framework 
# Site: http://www.instant2press.com
# Site: http://code.google.com/p/instant-press/
# Copyright (c) 2010- Mulone, Pablo Martín (mulone.martin@gmail.com)
# License: GPL, General Public License v.2
# Visit: www.web2py.com or Groups: http://groups.google.com/group/web2py and http://groups.google.com/group/web2py-usuarios  

import os
def _write_content(controller,function,arg,title,subtitle,view,format,lang,body,created_by):
    id_plugin_flatpage = db.plugin_flatpage.insert(controller=controller,
                                                    function=function,
                                                    arg=arg,
                                                    title=title,
                                                    subtitle=subtitle,
                                                    view=view,
                                                    format=format,
                                                    lang=lang,
                                                    body=body,
                                                    created_by=created_by)
    return id_plugin_flatpage
   
#if there are no plugin_flatpage pages then create some 
def _insert_uc_flatpage_default_content():
    pagecount = db(db.plugin_flatpage.id>0).count() #GAE
    if pagecount <=0:

        controller  = 'plugin_uc_flatpage'
        function    = 'index'
        arg         = request.args and request.args[0]

        #First post
        title       = 'about plugin_uc_flatpage'
        subtitle    = 'general information of the plugin_uc_flatpage'
        view        = FLATPAGE_VIEW
        format      = "MARKMIN"
        lang        = session._language
        about_path = os.path.join(cwd,'applications',request.application, 'static', plugin_name, 'about')
        body        =open(about_path,'r').read()

#        created_on  = '2010-08-24 18:02:00'
        created_by = _fill_get_admin_guy()
              
        _write_content(controller,function,arg,title,subtitle,view,format,lang,body,created_by)

################################################################
#plugin_uc_flatpage/init_5_add_admin_user_0_plugin_uc_flatpage.py 
#
# This code was lifted and modified from the instant-press application by Pablo Martin.
# Code modification where made by Christopher Steel of Voice of Access and remain:
# License: GPL, General Public License v.2
#
# Here is Pablo's header from the original code.
#
# -*- coding: utf-8 -*-
# Instant Press, site that work out the box. Blog system for Web2py Framework 
# Site: http://www.instant2press.com
# Site: http://code.google.com/p/instant-press/
# Copyright (c) 2010- Mulone, Pablo Martín (mulone.martin@gmail.com)
# License: GPL, General Public License v.2
# Visit: www.web2py.com or Groups: http://groups.google.com/group/web2py and http://groups.google.com/group/web2py-usuarios  

#Important constant
IS_FIRST_TIME = True #this is the first time create default data, after the first run, put this to False to reduce innecesary queries 

#please change the default password after first login,
#better register new user and give admin access, then disable
#this admin.
#WARNING: NEVER but never: use in production any password exposed in this constants
DEFAULT_ADMIN_EMAIL = "test@tester.com" #default_admin_email
DEFAULT_ADMIN_PASSWORD = "test" #default_admin_password

target_value_1 = 'plugin_uc_flatpage'
target_value_2 = 'Users who are members of the group, %s, have full CRUD (create, read , update and delete) to the tag data that this application has full CRUD access to.' % (target_value_1)
target_value_1_found='None'

DEFAULT_GROUPADMIN = "plugin_uc_flatpage" #default_groupadmin

#we need some information in the database to work correctly, 
#this fill with default information, the first time.
if IS_FIRST_TIME:
    
    if _is_no_user_in_db(): #if there are not user in db, so i think is the first time and create default values   
        
        #we need an admin
        _fill_required_admin()

        #This will create the initial content for the uc_flatpage page used to orient the user/developer
        _insert_uc_flatpage_default_content()


# coding: utf8
# models/plugin_plugin.py
## This file was created using static/plugin_plugin/model_template using the plugin_plugin
# copyright Christopher Steel, 2011, Voice of Access
#########################################
# initialization.py
import os
cwd = os.getcwd()
current_app = os.path.join(cwd,'applications',request.application)
initialization_file_path = os.path.join(current_app,'models','000_uc_initialization.py')

#############################
# ensure initialization file
#
def create_initialization_file():
    if not os.path.exists(initialization_file_path):
        our_file = open(initialization_file_path,"w")
        our_text = '# file created by plugin_uc_flatpage\n'
        print('created %s' % initialization_file_path)
    else:
        if 'plugin_debug_enabled' in globals():
            if plugin_debug_enabled == True:
                print('found %s' % initialization_file_path)

def append_initialization_file(append):
    our_file = open(initialization_file_path,"w")
    our_file.writelines(append)
    our_file.close()
    if 'plugin_debug_enabled' in globals():
        if plugin_debug_enabled == True:
            print('appended %s to %s' % (append,initialization_file_path))

if not 'initialization_file_created' in globals():
    create_initialization_file()
    append = '# entry created by plugin_uc_flatpage\n'
    append_initialization_file(append)
    append = "initialization_file_created = True\n"
    append_initialization_file(append)
else:
    if 'plugin_debug_enabled' in globals():
        if plugin_debug_enabled == True:
            print("found 'initialization_file_created' in globals")

if not 'group_plugin_uc_flatpage_admin_created' in globals():
    if not db(db.auth_group.role=='plugin_uc_flatpage_admin').select():
        db.auth_group.insert(role='plugin_uc_flatpage_admin',description='user to administer plugin_uc_flatpage')
    else:
        if 'plugin_debug_enabled' in globals():
            if plugin_debug_enabled == True:
                print("found db.auth_group.role=='admin_plugin_plugin' in database")
    append_initialization_file('# entry created by plugin_uc_flatpage\n')
    append_initialization_file('group_plugin_uc_flatpage_admin_created = True\n')
else:
    if 'plugin_debug_enabled' in globals():
        if plugin_debug_enabled == True:
            print('found "group_plugin_uc_flatpage_admin_created" in globals')

###############################################
# ensure we have an config group for our plugin
#
if not 'group_plugin_uc_flatpage_config_created' in globals():
    if not db(db.auth_group.role=='plugin_uc_flatpage_config').select(): 
        db.auth_group.insert(role='plugin_uc_flatpage_config',description='user to configure plugin_uc_flatpage')
        append = '# entry created by plugin_uc_flatpage\n'
        append_initialization_file(append)
        append = 'group_plugin_uc_flatpage_config_created = True\n'
        append_initialization_file(append)
    else:
        if 'plugin_debug_enabled' in globals():
            if plugin_debug_enabled == True:
                print("found db.auth_group.role=='config_plugin_plugin' in database")
else:
    if 'plugin_debug_enabled' in globals():
        if plugin_debug_enabled == True:
            print('found "group_plugin_uc_flatpage_config_created" in globals')

#################################################################
# Ensure we have the global variable 'plugin_uc_flatpage_installed'
#
if not 'plugin_uc_flatpage_installed' in globals():
    our_file = open(initialization_file_path,"a")
    append = '# entry created by plugin_uc_flatpage\n'
    append_initialization_file(append)
    append = 'plugin_uc_flatpage_installed = True\n'
    append_initialization_file(append)
else:
    if 'plugin_debug_enabled' in globals():
        if plugin_debug_enabled == True:
            print('found "models/plugin_uc_flatpage/initialization.py" in globals')
            print('found "plugin_uc_flatpage_installed" in globals')
